const TOKEN_KEY = 'token'
const config = process.env.APP_CONFIG as unknown as Record<string, string>
console.log('config', config)

const query = location.search
  .slice(1)
  .split('&')
  .reduce<Record<string, string>>((query, item) => {
    const [rawKey, rawValue] = item.split('=')
    const key = rawKey ?? ''
    const value = decodeURIComponent(rawValue ?? '')
    if (!key && !value) return query
    return { ...query, [key.toLowerCase()]: value }
  }, {})
console.log('query', query)

function failed() {
  location.replace((config.EXTERNAL_AUTH_PAGE ??'') || '../')
}

async function confirm() {
  const encryptId = query['encrypt-id'] ?? query['encryptid'] ?? ''
  if (!encryptId) return void failed()

  const request = await fetch(`${(config.API ?? '') || '/gnapi'}/User/CheckCustomLogin`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ EncryptId: encryptId })
  })
  try {
    if (request.status === 200) {
      const response = (await request.json()) as { code: number, data?: { token: string }, msg: string }
      if (response.code === 0 && response.data && response.data.token) {
        localStorage.setItem(TOKEN_KEY, response.data.token)
        location.replace('../')
        return
      }
    }
  } catch(e) {
    console.error(e)
  }

  failed()
}
void confirm()
